package com.jmga.ecogasfinder.services;

import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.jmga.ecogasfinder.providers.GasFinderProvider;

public class CleaningService extends Service {
	public static final String KEY_WHEN = "KEY_WHEN";
	public static final String KEY_CHECKBOX_FAVOURITE = "KEY_CHECKBOX_FAVOURITE";
	public static final String KEY_CHECKBOX_PRICES = "KEY_CHECKBOX_PRICES";
	
	public static final int TIME_ALL          = 1;
	public static final int TIME_ONE_DAY      = 2;
	public static final int TIME_ONE_WEEK     = 3;
	public static final int TIME_ONE_MONTH    = 4;
	public static final int TIME_THREE_MONTHS = 5;
	public static final int TIME_ONE_YEAR     = 6;
	
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(getClass().getName(), "onStartCommand: " + intent.getAction() + "Flags: " + flags + " startId " + startId);
		if ((flags & START_FLAG_RETRY) == 0) {
			// if it's a restart, do something.
		} else {
			// Alternative background process.
		}
		int when = intent.getIntExtra(CleaningService.KEY_WHEN, 7);
		boolean cleanFavourites = intent.getBooleanExtra(CleaningService.KEY_CHECKBOX_FAVOURITE, false);
		boolean cleanPrices = intent.getBooleanExtra(CleaningService.KEY_CHECKBOX_PRICES, false);
		String timeCondition = "";
		
		switch (when) {
			case TIME_ALL:
				timeCondition = "1 = 1";
				cleaningFrequencies();
				break;
			case TIME_ONE_DAY:
				timeCondition = "(julianday('now') - julianday(datetime(" + GasFinderProvider.KEY_DATE + "/1000, 'unixepoch'))) > 1";
				break;
			case TIME_ONE_WEEK:
				timeCondition = "(julianday('now') - julianday(datetime(" + GasFinderProvider.KEY_DATE + "/1000, 'unixepoch'))) > 7";
				break;
			case TIME_ONE_MONTH:
				timeCondition = "(julianday('now') - julianday(datetime(" + GasFinderProvider.KEY_DATE + "/1000, 'unixepoch'))) > 30";
				break;
			case TIME_THREE_MONTHS:
				timeCondition = "(julianday('now') - julianday(datetime(" + GasFinderProvider.KEY_DATE + "/1000, 'unixepoch'))) > 90";
				break;
			case TIME_ONE_YEAR:
				timeCondition = "(julianday('now') - julianday(datetime(" + GasFinderProvider.KEY_DATE + "/1000, 'unixepoch'))) > 365";
				break;
		}
		
		if(cleanFavourites) {
			cleaningFavourites(timeCondition);
		}
		
		if(cleanPrices) {
			cleaningPrices(timeCondition, null);
		}
		
		return START_STICKY;
	}
	
	private void cleaningFrequencies() {
		int deletedRows = getContentResolver().delete(GasFinderProvider.CONTENT_URI_FREQUENCY, null, null);
		Log.d(getClass().getName(), "Frequencies rows deleted = " + deletedRows);
		String whereNotFavourite = GasFinderProvider.KEY_FAVOURITE + " = 0";
		int deletedStationsRows = getContentResolver().delete(GasFinderProvider.CONTENT_URI_STATIONS, whereNotFavourite, null);
		Log.d(getClass().getName(), "No Favourites stations deleted = " + deletedStationsRows);
	}

	private void cleaningFavourites(String timeCondition) {
		FavouritesCleanerTask favouritesCleaner = new FavouritesCleanerTask();
		Object[] parameters = new Object[1];
		parameters[0] = timeCondition;
		
		favouritesCleaner.execute(parameters);
	}
	
	private void cleaningPrices(String timeCondition, String station) {
		PricesCleanerTask pricesCleaner = new PricesCleanerTask();
		Object[] parameters = new Object[2];
		parameters[0] = timeCondition;
		parameters[1] = station;
		
		pricesCleaner.execute(parameters);
	}
	
	private class FavouritesCleanerTask extends AsyncTask<Object, Void, Void> {
		@Override
		protected Void doInBackground(Object... params) {
			String whereTime = (String) params[0];
			String whereFavourite = GasFinderProvider.KEY_FAVOURITE + " = 1";
			Cursor cursor = getContentResolver().query(GasFinderProvider.CONTENT_URI_STATIONS, null, whereFavourite, null, null);
			
			if(cursor.getCount() != 0) {
				for(int i=0; cursor.moveToNext(); i++) {
			        double xCoord = cursor.getDouble(cursor.getColumnIndexOrThrow(GasFinderProvider.KEY_X_COORD));
			        double yCoord = cursor.getDouble(cursor.getColumnIndexOrThrow(GasFinderProvider.KEY_Y_COORD));
			        
			        String whereStation = GasFinderProvider.KEY_STATION + " = '" + xCoord + yCoord + "'";
			        cleaningPrices(whereTime, whereStation);
				}
				int deletedRows = getContentResolver().delete(GasFinderProvider.CONTENT_URI_STATIONS, whereFavourite, null);
				Log.d(getClass().getName(), "Favourites rows deleted = " + deletedRows);
			}
			return null;
	    }
		
		@Override
	    protected void onProgressUpdate(Void... values) {

	    }
	
	    @Override
	    protected void onPostExecute(Void result) {
			Intent intentLoading = new Intent(StationUpdaterService.SHOW_TOP_TEN);
			Log.d(getClass().getName(), "sendBroadcast:" + StationUpdaterService.SHOW_TOP_TEN);
			sendBroadcast(intentLoading);
	    	stopSelf();
	    }
	}

	private class PricesCleanerTask extends AsyncTask<Object, Void, Void> {
		@Override
		protected Void doInBackground(Object... params) {
			String whereTime = (String) params[0];
			String whereStation = null, where = whereTime;
			
			if(params[0] != null) {
				whereStation = (String) params[1];
				if(whereStation != null) {
					where += " AND " + whereStation;
				}
			}
			
			int deletedPriceRows = getContentResolver().delete(GasFinderProvider.CONTENT_URI_PRICES, where, null);
			Log.d(getClass().getName(), "PriceRows deleted = " + deletedPriceRows);
			
			return null;
	    }
		
		@Override
	    protected void onProgressUpdate(Void... values) {

	    }
	
	    @Override
	    protected void onPostExecute(Void result) {
			Intent intentLoading = new Intent(StationUpdaterService.SHOW_TOP_TEN);
			Log.d(getClass().getName(), "sendBroadcast:" + StationUpdaterService.SHOW_TOP_TEN);
			sendBroadcast(intentLoading);
	    	stopSelf();
	    }
	}	
}
